<template>
    <el-form :model="attendSearchForm" :inline="true" style="margin-bottom: 10px;" class="demo-form-inline">
        <el-form-item label="考勤日期">
            <el-date-picker v-model="attendSearchForm.date" value-format="YYYY-MM-DD"  type="daterange"
                placeholder="选择日期" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                style=" margin-left: 10px"/>
        </el-form-item>
        <el-form-item label="考勤状态">
            <el-select v-model="attendSearchForm.empAttendanceStatus" style="width: 100px;" placeholder="请选择">
                <el-option label="迟到" value="1"></el-option>
                <el-option label="缺勤" value="2"></el-option>
                <el-option label="请假" value="3"></el-option>
                <el-option label="考勤成功" value="4"></el-option>
                <el-option label="未考勤" value="5"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="getEmpAttendanceMsg">查询</el-button>
            <el-button type="info" @click="clearForm">清空</el-button>
        </el-form-item>
    </el-form>
    <el-table :data="tableData" border style="width: 75%">
        <el-table-column type="index" label="id" width="50" />
        <el-table-column prop="attendanceName" label="考勤名称" width="180" />
        <el-table-column prop="attendanceDate" label="考勤日期" width="180" />
        <el-table-column prop="endAttendanceTime" label="考勤截止时间" width="180">
            <template #default="scope">
                <span>{{moment(scope.row.endAttendanceTime).format("YYYY-MM-DD HH:mm:ss")}}</span>
            </template>
        </el-table-column>
        <el-table-column prop="empAttendanceStatus" label="当前考勤状态" width="180">
            <template #default="scope">
                <span v-if="scope.row.empAttendanceStatus === 1">迟到</span>
                <span v-else-if="scope.row.empAttendanceStatus === 2">缺勤</span>
                <span v-else-if="scope.row.empAttendanceStatus === 3">请假</span>
                <span v-else-if="scope.row.empAttendanceStatus === 4">考勤成功</span>
                <span v-else-if="scope.row.empAttendanceStatus === 5">未考勤</span>
            </template>
        </el-table-column>
        <el-table-column label="考勤操作">
            <template #default="scope">
                <el-button type="primary" @click="signIn(scope.row.endAttendanceTime,scope.row.id,scope.row.empAttendanceStatus)">点击签到</el-button>
            </template>
        </el-table-column>
    </el-table>
    <div style="margin-top: 10px;">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
            :page-sizes="[5,10,15,20]" :size="size" :disabled="disabled" :background="background"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, watch } from 'vue'
import { ElTable, ElMessage, UploadProps, dayjs } from 'element-plus'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import axios from '@/utils/request';
import moment from 'moment';
import {empAccount} from '@/store';
const accountStore = empAccount()
//获取当前员工账号
const account = ref(accountStore.$state.account)
const total = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const size = ref<ComponentSize>('default')
const disabled = ref(false)
const tableData = ref([])
const background = ref(true)
const attendSearchForm = ref({
    date: ['',''],
    empAttendanceStatus: '',
})
//清空表单
const clearForm = () => {
    attendSearchForm.value.date = ['','']
    attendSearchForm.value.empAttendanceStatus = ''
    // 清空表单后重新获取数据
    getEmpAttendanceMsg()
}
//页数变化
const handleCurrentChange = (val: number) => {
    currentPage.value = val
    getEmpAttendanceMsg()
}
//每页显示条数变化
const handleSizeChange = (val: number) => {
    pageSize.value = val
    getEmpAttendanceMsg()
}
//生命周期函数，一挂载组件就获取表格数据
onMounted(() => {
    getEmpAttendanceMsg()
    // 开始心跳检查
    startHeartbeatCheck()
})
//获取该员工的考勤数据(包括查询)
const getEmpAttendanceMsg = async () => {
    try {
        const result = await axios.get(`/emp/attendance?page=${currentPage.value}&pageSize=${pageSize.value}&startDate=${attendSearchForm.value.date[0].replace(/ /g, "")}&endDate=${attendSearchForm.value.date[1].replace(/ /g, "")}&empAttendanceStatus=${attendSearchForm.value.empAttendanceStatus}&account=${account.value}`)
        if (result.data.code === 1) {
            //查询成功提示
            if(attendSearchForm.value.date[0] !== '' || attendSearchForm.value.date[1] !== '' || attendSearchForm.value.empAttendanceStatus!== ''){
                ElMessage.success('查询成功')
            }
            tableData.value = result.data.data.rows
            total.value = result.data.data.total
        } else {
            ElMessage.error('查询失败')
        }
    } catch (error) {
        ElMessage.error('获取信息失败')
    }
}
let heartbeatInterval: any; // 用于存储定时器的标识，方便后续清除定时器

const startHeartbeatCheck = () => {
    // 清除之前的定时器，避免重复启动
    clearInterval(heartbeatInterval);

    if (tableData.value.length > 0) {
        // 每一秒执行一次检查
        heartbeatInterval = setInterval(() => {
            checkAbsenteeism();
        }, 1000);
    }
};

// 监视表格数据的变化，动态启动或停止心跳检查
watch(tableData, () => {
    startHeartbeatCheck();
});

// 检查员工是否缺勤的具体函数
const checkAbsenteeism = () => {
    const currentTime = moment();
    tableData.value.forEach((row: any) => {
        const endAttendanceTime = moment(row.endAttendanceTime);
        // 判断当前时间是否超过考勤截止时间，且当前状态不是缺勤并且只能是未考勤
        if (currentTime.isAfter(endAttendanceTime) && row.empAttendanceStatus!== 2 && row.empAttendanceStatus=== 5) {
            // 将该员工的考勤状态改为缺勤，并发送给后端
            const empId = row.id;
            updateAttendanceStatus(empId, 2);
        }
    });
};

// 用于更新考勤状态并发送给后端的函数
const updateAttendanceStatus = async (empId: any, newStatus: number) => {
    try {
        const result = await axios.put('/emp/attendance', {
            id: empId,
            empAttendanceStatus: newStatus
        });
        if (result.data.code === 1) {
            // 这里可以根据需求决定是否刷新页面数据，如果需要实时更新展示可调用
            getEmpAttendanceMsg();
        } else {
            ElMessage.error('更新考勤状态失败');
        }
    } catch (error) {
        ElMessage.error('更新考勤状态出现异常');
    }
};
//点击签到后调用的函数
const signIn = async (endAttendanceTime: any, empId: any,empAttendanceStatusOld:any) => {
    //签到成功之后不能再签到
    if(empAttendanceStatusOld === 4 || empAttendanceStatusOld === 1){
        ElMessage.warning('已经签到了哦~~~~')
        return
    }else if(empAttendanceStatusOld === 3){
        ElMessage.warning('请假中，不能签到哦~~~~')
        return
    }else if(empAttendanceStatusOld === 2){
        ElMessage.warning('已经缺勤了哦~~~~')
        return
    }
    // 获取当前时间（这里使用moment库获取当前时间，你也可以根据实际情况选择其他方式，比如dayjs等）
    const currentTime = moment();
    // 将endAttendanceTime转换为时间戳，先将其转换为moment对象，再获取时间戳
    const endTimeStamp = moment(endAttendanceTime).valueOf();
    // 获取当前时间的时间戳
    const currentTimeStamp = currentTime.valueOf();
    // 比较时间戳和当前签到时间的大小判断签到后的状态
    let empAttendanceStatus = 0;
    if (currentTimeStamp <= endTimeStamp) {
        empAttendanceStatus = 4;// 考勤成功
    } else {
        empAttendanceStatus = 1;// 迟到
    }
    // 将签到后的状态以及相关考勤记录的id等信息发送给后端（这里假设后端接口接收status和attendanceId参数，你需要根据实际后端接口调整）
    try {
        const result = await axios.put('/emp/attendance', {
            id: empId,
            empAttendanceStatus: empAttendanceStatus
        });
        if (result.data.code === 1) {
            ElMessage.success('签到成功');
            // 签到成功后重新获取考勤信息，更新表格显示
            getEmpAttendanceMsg();
        } else {
            ElMessage.error('签到失败');
        }
    } catch (error) {
        ElMessage.error('签到出现异常');
    }
};
</script>

<style></style>